package com.tensquare.article.service;

import com.tensquare.article.controller.CatException;
import com.tensquare.article.pojo.Comment;
import com.tensquare.article.repository.CommentRepository;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.swing.event.CaretEvent;
import java.util.List;
import java.util.Optional;

@Service
public class CommentService {

    @Autowired
    CommentRepository commentRepository;

    @Autowired
    IdWorker idWorker;

    //查询所有
    public List<Comment> findAll(){
        List<Comment> all = commentRepository.findAll();
        return all;
    }

    //通过id查询
    public Comment findById(String id){
        Optional<Comment> byId = commentRepository.findById(id);
        if(byId.isPresent()){
            Comment comment = byId.get();
            return comment;
        }else {
            return null;
        }
    }

    //删除
    public void delete(String id){
        commentRepository.deleteById(id);
    }

    //新增
    public void add(Comment comment){
        //生成分布式id
        String s = idWorker.nextId() + " ";
        comment.set_id(s);
        //初始化点赞数
        comment.setThumbup(0);
        commentRepository.insert(comment);
    }

    //修改
    public void update(String id,Comment comment){
        //先进行查询
        Comment byId = findById(id);
        if(byId==null){
            //修改失败
            CatException.CatEx(new Result(false, StatusCode.ERROR,"修改失败"));
        }else {
            comment.set_id(id);
            commentRepository.save(comment);
        }
    }

    //评论点赞
    public void addThumbup(String id){
        //通过id查找文章对象
        Comment byId = findById(id);
        if(byId==null){
            CatException.CatEx(new Result(false, StatusCode.ERROR,"点赞失败"));
        }else {
            //点赞数加一
            byId.setThumbup(byId.getThumbup()+1);
            commentRepository.save(byId);
        }
    }


}
